<template>
    <div class="map-content">
        <div id="Amap-flyArea"></div>
        <div class="tip">
            <input type="text" id="tipinput" name="tipinput" value="" v-model="keywords" placeholder="请输入关键字：(选定后搜索)"/>
        </div>
        <ul class="tile-type">
            <li class="satellite-tile active">
                <img src="../assets/images/star-tiles.png" alt="卫星地图">
                <span>卫星地图</span>
            </li>
            <li class="street-tile">
                <img src="../assets/images/plan-tiles.png" alt="街道地图">
                <span>街道地图</span>
            </li>
        </ul>
        <div class="area-info">
            <div class="area-info-container">
                <p class="the-area">
                    <span>大致位置：</span>
                    <span class="area-info_loc">{{locations}}</span>
                </p>
                <div class="area-detail">
                    <div>
                        <span class="area-info_span">圈选面积为：</span>
                        <span class="area-info_a">{{area}}</span>
                        <span class="area-info_unit"> 平方公里</span>
                    </div>
                </div>
            </div>
            <div class="btns">
                <button id="closeLayer">确定</button>
                <button id="clearMarker">清除瞄点</button>
                <button id="showPath" class="hidden">显示瞄点区域</button>
            </div>
        </div>
    </div>
</template>

<script>
    export default {
        name: 'maps',
        props: ['lnglat', 'typeId'],
        data() {
            return {
                keywords: '',
                area: 0,//面积
                locations: '',//位置
            }
        },
        methods: {
            setArea(data) {
                this.$emit("setArea", data)
            },
            setLnglat(data) {
                this.$emit("setLnglat", data)
            },
            setLength(data) {
                this.$emit("setLength", data)
            },
            setLocations(data) {
                this.$emit("setLocations", data)
            }
        },

        mounted() {
            let that = this
            var orderType = this.typeId

            var tipinput = document.getElementById('tipinput')

            var tilesType = document.querySelector('.tile-type')
            var satelliteTile = document.querySelector('.satellite-tile')
            var streetTile = document.querySelector('.street-tile')
            var btn_close = document.getElementById("closeLayer");
            var btn_clear = document.getElementById("clearMarker");
            var btn_path = document.getElementById("showPath");

            var cache_polygon, cache_polyline, cache_marker = []
            var polygon, polyline

            var isUpdate = false
            let modalClose = false

            tilesType.addEventListener('click', function (e) {
                e.stopPropagation()
                !e.target.classList.contains('active') &&
                e.target.classList.add('active')
            })

            satelliteTile.onclick = e => {
                satelliteTile.classList.add('active')
                streetTile.classList.remove('active')
                satellite.show()
            }
            streetTile.onclick = e => {
                streetTile.classList.add('active')
                satelliteTile.classList.remove('active')
                satellite.hide()
            }

            document.onclick = e => {
                !e.target.classList.contains('tile-type') &&
                tilesType.classList.remove('active')
            }

            let map = new AMap.Map('Amap-flyArea', {
                resizeEnable: true,
                zoom: 17
            })

            let satellite = new AMap.TileLayer.Satellite({
                map: map,
            })

            AMap.plugin('AMap.Geolocation', function() {
                let geolocation = new AMap.Geolocation({
                    enableHighAccuracy: true,
                    timeout: 10000,
                    zoomToAccuracy: true,
                    showButton: false,
                });
                map.addControl(geolocation);
                geolocation.getCurrentPosition(function(status, result){
                    if(status == 'complete'){
                        return true
                    }
                });
            });

            let geocoder
            if (!geocoder) {
                geocoder = new AMap.Geocoder();
            }

            if (orderType === 5) {
                document.querySelector('.area-info_span').innerHTML = '划线长度为：'
                document.querySelector('.area-info_unit').innerHTML = '公里'
                document.getElementById('showPath').classList.toggle('hidden')
            }
            if (orderType !== 4 && orderType !== 5) {
                document.getElementById('showPath').classList.toggle('hidden')
            }
            if (orderType === 4) {
                document.querySelector('.area-info_span').innerHTML = '描点个数：'
                document.querySelector('.area-info_unit').innerHTML = '个'
            }

            if (that.lnglat !== '') {
                let cachepath = []
                let cachelnglat = JSON.parse(that.lnglat)

                if (orderType == 1 || orderType == 2 || orderType == 3) {
                    cachepath = [];
                    cachelnglat.forEach(value => {
                        cachepath.push([value.lng, value.lat])
                    })
                    cache_polygon = new AMap.Polygon({
                        path: cachepath,
                        isOutline: true,
                        borderWeight: 3,
                        strokeColor: '#FF33FF',
                        strokeWeight: 6,
                        strokeOpacity: 0.2,
                        fillOpacity: 0.4,
                        fillColor: '#1791fc',
                        zIndex: 50,
                    });

                    cache_polygon.setMap(map)
                    // 缩放地图到合适的视野级别
                    map.setFitView([cache_polygon])
                }
                if (orderType == 5) {

                    cache_polyline = new AMap.Polyline({
                        path: cachelnglat,
                        borderWeight: 2, // 线条宽度，默认为 1
                        strokeColor: 'red', // 线条颜色
                        lineJoin: 'round' // 折线拐点连接处样式
                    });
                    // map.add(polyline);
                    cache_polyline.setMap(map)

                }
                if (orderType == 4) {
                    cachelnglat.forEach(value => {
                        let tempMark = new AMap.Marker({
                            position: value,
                        });
                        cache_marker.push(tempMark)
                        map.add(tempMark);
                    })
                }
            }

            let allPoint = []
            let markers = []
            let lines = []
            let lines_dashed = []


            map.getCity(result => {
                that.locations = result.city
            })


            map.on('click', function (e) {
                if (modalClose) {
                    btn_clear.click()
                    modalClose = false
                }
                if (tilesType.classList.contains('active')) {
                    return
                }

                isUpdate = true
                cache_polygon && map.remove(cache_polygon)

                cache_polyline && map.remove(cache_polyline)

                cache_marker && map.remove(cache_marker)
                /*获取地址*/
                geocoder.getAddress([e.lnglat.getLng(), e.lnglat.getLat()], function (status, result) {
                    if (status === 'complete' && result.info === 'OK') {
                        // result为对应的地理位置详细信息
                        that.locations = result.regeocode.formattedAddress
                    }
                })

                switch (orderType) {
                    case 1:
                    case 2:
                    case 3:
                        if (polygon) {
                            map.remove(polygon)
                        }
                        if (lines_dashed.length > 0) {
                            map.remove(lines_dashed)
                            lines_dashed.length = 0

                        }
                        var marker = new AMap.Marker({
                            position: new AMap.LngLat(e.lnglat.getLng(), e.lnglat.getLat()),
                            draggable: false,
                            extData: {
                                id: markers.length
                            }
                        }).on('dragend', function (event) {
                            console.log(event)
                        });
                        markers.push(marker)
                        map.add(marker)


                        if (markers.length > 1) {
                            var path = [
                                new AMap.LngLat(markers[markers.length - 2].getPosition().getLng(), markers[markers.length - 2]
                                    .getPosition().getLat()),
                                new AMap.LngLat(marker.getPosition().getLng(), marker.getPosition().getLat())
                            ]
                            var polyline_temp = new AMap.Polyline({
                                path: path,
                                borderWeight: 2, // 线条宽度，默认为 1
                                strokeColor: 'red', // 线条颜色
                                lineJoin: 'round' // 折线拐点连接处样式
                            });
                            // 将折线添加至地图实例

                            lines.forEach(value => {
                                value.show()
                            })
                            map.add(polyline_temp);
                            lines.push(polyline_temp)

                            // 添加虚线
                            if (markers.length > 2) {
                                var dashed = [
                                    new AMap.LngLat(marker.getPosition().getLng(), marker.getPosition().getLat()),
                                    new AMap.LngLat(markers[0].getPosition().getLng(), markers[0].getPosition().getLat())
                                ]

                                var polyline_dashed = new AMap.Polyline({
                                    path: dashed,
                                    borderWeight: 2, // 线条宽度，默认为 1
                                    strokeColor: 'green', // 线条颜色
                                    lineJoin: 'round', // 折线拐点连接处样式
                                    strokeStyle: 'dashed'
                                });
                                map.add(polyline_dashed);
                                lines_dashed.push(polyline_dashed)
                            }

                        }
                        break;
                    case 5:
                        polyline && map.remove(polyline)
                        var marker = new AMap.Marker({
                            position: new AMap.LngLat(e.lnglat.getLng(), e.lnglat.getLat()),
                            draggable: false,
                            extData: {
                                id: markers.length
                            }
                        }).on('dragend', function (event) {
                            console.log(event)
                        })
                        markers.push(marker)
                        map.add(marker)


                        lines_dashed.forEach(value => {
                            value.show()
                        })
                        if (markers.length % 2 == 0) {
                            var path = [
                                new AMap.LngLat(markers[markers.length - 2].getPosition().getLng(), markers[markers.length - 2]
                                    .getPosition().getLat()),
                                new AMap.LngLat(marker.getPosition().getLng(), marker.getPosition().getLat())
                            ]
                            var polyline_temp = new AMap.Polyline({
                                path: path,
                                borderWeight: 2, // 线条宽度，默认为 1
                                strokeColor: 'red', // 线条颜色
                                lineJoin: 'round', // 折线拐点连接处样式
                                strokeStyle: 'dashed'
                            });

                            map.add(polyline_temp);
                            lines_dashed.push(polyline_temp)
                        }
                        break;
                    case 4:
                        var marker = new AMap.Marker({
                            position: new AMap.LngLat(e.lnglat.getLng(), e.lnglat.getLat()),
                            draggable: false,
                            extData: {
                                id: markers.length
                            }
                        }).on('dragend', function (event) {
                            console.log(event)
                        })
                        markers.push(marker)

                        that.area = markers.length
                        map.add(marker)
                        break;
                }
            })
            /***搜索****/
            AMap.plugin(['AMap.Autocomplete', 'AMap.PlaceSearch'], function () {
                var autoOptions = {
                    city: "全国", //城市，默认全国
                    input: "tipinput" //使用输入的input的id
                };
                let autocomplete = new AMap.Autocomplete(autoOptions);
                AMap.event.addListener(autocomplete, "select", function (e) {
                    //TODO 针对选中的poi实现自己的功能
                    var loc = e.poi.location
                    var lnglat = [loc.lng, loc.lat]
                    that.locations = e.poi.district
                    map.panTo(lnglat)
                });
            });

            btn_close.addEventListener('click', function () {
                modalClose = true
                if (orderType != 4 && orderType != 5) {
                    btn_path.click()
                }

                if (orderType == 5) {
                    var lineLength = 0

                    markers.forEach((value, index) => {
                        if (index % 2 !== 0 && index !== 0) {
                            lineLength += +AMap.GeometryUtil.distance(value.getPosition(), markers[index - 1].getPosition())
                        }

                        allPoint.push(value.getPosition())
                    })

                    that.area = (lineLength / 1000).toFixed(2)
                }
                if (orderType == 4) {
                    markers.forEach(value => {
                        allPoint.push(value.getPosition())
                    })

                    that.area = allPoint.length
                    that.setArea(that.area)
                }

                allPoint.length !== 0 &&
                geocoder.getAddress([allPoint[0].lng, allPoint[0].lat], function (status, result) {
                    if (status === 'complete' && result.info === 'OK') {
                        // result为对应的地理位置详细信息
                        that.setLocations(result.regeocode.formattedAddress)
                    }
                })

                that.setLocations(that.locations)
                if (orderType == 5) {
                    that.setArea(that.area)
                    that.setLength(that.area)
                } else {
                    that.setArea(that.area)
                }

                that.setLnglat(JSON.stringify(allPoint))
            });

            btn_clear.addEventListener('click', function () {
                isUpdate = true
                map.remove(markers)
                map.remove(lines)
                map.remove(lines_dashed)

                allPoint = []

                lines.length = 0
                lines_dashed.length = 0
                markers.length = 0

                polygon && map.remove(polygon)

                polyline && map.remove(polyline)

                cache_polygon && map.remove(cache_polygon)

                cache_polyline && map.remove(cache_polyline)

                cache_marker && map.remove(cache_marker)

                that.area = 0
            })

            btn_path.addEventListener('click', function () {
                var path = []

                polygon && map.remove(polygon)

                if (lines.length > 0) {
                    // map.remove(lines)
                    lines.forEach(value => {
                        value.hide()
                    })
                }
                if (lines_dashed.length > 0) {
                    // map.remove(lines_dashed)
                    lines_dashed.forEach(value => {
                        value.hide()
                    })
                }
                markers.forEach(value => {
                    var mloc = value.getPosition();

                    path.push(new AMap.LngLat(mloc.getLng(), mloc.getLat()))
                })

                if (orderType == 5) {
                    polyline = new AMap.Polyline({
                        path: path,
                        borderWeight: 2, // 线条宽度，默认为 1
                        strokeColor: 'red', // 线条颜色
                        lineJoin: 'round' // 折线拐点连接处样式
                    })

                    map.add(polyline)
                    var lineLengthAll = 0
                    markers.forEach((value, index) => {

                        if (index % 2 !== 0 && index !== 0) {
                            lineLengthAll += +AMap.GeometryUtil.distance(value.getPosition(), markers[index - 1].getPosition())
                        }
                    })

                    that.area = (lineLengthAll / 1e3).toFixed(2)
                } else {
                    polygon = new AMap.Polygon({
                        path: path,
                        isOutline: true,
                        fillColor: '#1791fc', // 多边形填充颜色
                        fillOpacity: 0.4,
                        borderWeight: 2, // 线条宽度，默认为 1
                        strokeColor: "#FF33FF", // 线条颜色
                        strokeOpacity: 0.2,
                        strokeWeight: 6,
                    });
                    map.add(polygon);

                    var area = polygon.getArea()
                    allPoint = polygon.getPath()

                    that.area = (area / 1e6).toFixed(2)
                }
            })
        },
    }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
    @import "../assets/scss/mixin";

    .map-content {
        width: 800px;
        color: #D7E1ED;
        display: flex;
        height: 600px;
        flex-direction: column;
        position: relative;
    }

    #Amap-flyArea {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%
    }

    .area-info {
        position: absolute;
        width: 100%;
        z-index: 200;
        bottom: 0;
        background: #292C35;
        display: flex;
        flex-direction: column;
        padding: 15px 20px;
        justify-content: space-around;
        & > .btns {
            margin-top: 15px;
        }
    }

    .area-info-container {
        display: flex;
        justify-content: space-between;
        align-items: baseline;
        & > p.the-area {
            flex: 1;
            @include fj(flex-start);
            & > span:first-child {
                width: 70px;
                white-space: nowrap;
                & + span {
                    flex: 1;
                }
            }
        }
    }

    .area-info .area-detail {
        display: flex;
        align-items: baseline;
        justify-content: space-between;
        flex: 1;
        margin-left: 20px;
    }

    .area-info select {
        background: #16181B;
        border: 1px solid #000000;
        color: #C8D0E9;
        height: 30px;
    }

    .area-info .hidden {
        display: none;
    }

    .btns {
        position: relative;
    }

    .btns > button {
        height: 32px;
        cursor: pointer;
        color: #C8D0E9;
        width: 120px;
        background: #1890FF;
        border-radius: 2px;
        border: none;
        /* position: absolute;
        right: 30px; */
        float: right;
        margin-right: 20px;
    }

    .btns > button:hover {
        background: #30679A;
    }

    #closeLayer {
        margin-right: 0;
    }

    .tip {
        background: #16181B;
        border: 1px solid #000000;
        color: #D7E1ED;
        box-shadow: 3px 4px 3px 0px #000000;
        position: absolute;
        top: 10px;
        left: 10px;
        border-radius: 5px;
        overflow: hidden;
        line-height: 20px;
    }

    .tip::after {
        content: '';
        position: absolute;
        right: 20px;
        top: 50%;
        margin-top: -10px;
        width: 20px;
        height: 20px;
        background: url('../assets/images/search.svg') no-repeat;
        background-position: center;

    }

    .tip input[type="text"] {
        color: #D7E1ED;
        background: #16181B;
        height: 25px;
        border: 0;
        padding-left: 5px;
        width: 280px;
        border-radius: 3px;
        outline: none;
    }

    .tile-type {
        position: absolute;
        top: 15px;
        right: 15px;
        opacity: 0.9;
        @include wh(44px, 44px);
        background: url('../assets/images/tiles-type.svg') center no-repeat;
        cursor: pointer;
        transition: height .5s ease-out;
        li {
            display: none;
        }
        &.active {
            background: #000000;
            box-shadow: 0 1px 2px 0 rgba(91, 91, 91, 0.50);
            list-style: none;
            padding: 10px 20px;
            margin: 0;
            @include fj(space-around);
            width: 160px;
            height: auto;
            li {
                @include fj();
                flex-direction: column;
                align-items: center;
                span {
                    margin-top: 10px;
                }
                &.active {
                    color: #4A90E2;
                    img {
                        border: 1px solid #4A90E2;
                    }
                }
            }
        }
    }
</style>